<template>
  <div class="article">
    <div style="font-size: xx-large">{{ title }}</div>
    <div>
      <Editor
        style="overflow-y: hidden"
        v-model="valueHtml"
        :defaultConfig="editorConfig"
        :mode="mode"
        @onCreated="handleCreated"
      />
      <div style="display: flex; flex-direction: column; align-items: start">
        <el-link
          target="_blank"
          v-for="file in fileList"
          :href="file.url"
          :key="file.url"
        >
          {{ file.name }}
        </el-link>
      </div>
    </div>
  </div>
</template>
<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor } from '@wangeditor/editor-for-vue'
import axios from 'axios'

export default {
  components: { Editor },
  setup() {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef()

    // 内容 HTML
    const valueHtml = ref('')
    const fileList = ref()
    const title = ref()
    onMounted(() => {})

    const editorConfig = {}
    editorConfig.readOnly = true

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value
      if (editor == null) return
      editor.destroy()
    })

    const handleCreated = (editor) => {
      editorRef.value = editor // 记录 editor 实例，重要！
    }

    const getArticleById = (id) => {
      axios
        .get('/api/getEssayById', {
          headers: {
            Authorization: `Bearer ${window.localStorage.getItem('token')}`,
          },
          params: {
            id: id,
          },
        })
        .then((res) => {
          title.value = res.data.data.title
          valueHtml.value = res.data.data.content

          fileList.value = eval(
            JSON.parse(JSON.stringify(res.data.data.attachment))
          )
        })
    }

    return {
      editorRef,
      valueHtml,
      mode: 'default', // 或 'simple'
      editorConfig,
      handleCreated,
      getArticleById,
      title,
      fileList,
    }
  },
}
</script>

<style scoped>
.article {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #fff;
  padding: 12px;
}
</style>
